package com.zys.controller;

import com.zys.constant.ErrorConstant;
import com.zys.constant.SuccessConstant;
import com.zys.convert.UserDtoConvert;
import com.zys.domain.Result;
import com.zys.domain.User;
import com.zys.dto.UserDTO;
import com.zys.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody UserDTO userDTO) {
         User newuser = userService.findUserByName(userDTO.getName());
         try {
            if (newuser != null) {
                throw new RuntimeException(ErrorConstant.USER_ALREADY_EXIST);
            }
//            User user = UserDtoConvert.INSTANCE.convertDtoToUser(userDTO);
            User user = new User();
//            user.setName(userDTO.getName());
//            user.setAge(userDTO.getAge());
             BeanUtils.copyProperties(userDTO,user);
            userService.addUser(user);
            return Result.success(SuccessConstant.USE_REGISTER_SUCCESS);
         }catch (RuntimeException e) {
             log.error(e.getMessage(),e);
             return Result.error(ErrorConstant.FAIL_TO_REGISTER);
         }

    }

    @PostMapping("/condition")
    public Result<List<User>> getUserByCondition(@RequestBody User user) {
        List<User> users = userService.selectUserByCondition(user);
        return Result.success(users);
    }

}
